package com.drinkdelivery.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.drinkdelivery.common.constants.ProductConstant;
import com.drinkdelivery.common.domain.*;
import com.drinkdelivery.common.domain.export.ProductsExport;
import com.drinkdelivery.common.request.ProductSkuRequest;
import com.drinkdelivery.common.request.ProductsRequest;
import com.drinkdelivery.common.response.ProductSpecResponse;
import com.drinkdelivery.common.response.ProductSpecValueResponse;
import com.drinkdelivery.common.response.ProductsDetailsResponse;
import com.drinkdelivery.common.utils.file.FileUtils;
import com.drinkdelivery.service.IProductSkuService;
import com.drinkdelivery.service.IProductSkuSpecValueService;
import com.drinkdelivery.service.IProductSpecService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.drinkdelivery.mapper.ProductsMapper;
import com.drinkdelivery.service.IProductsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 商品Service业务层处理
 *
 * @author lzh
 * @date 2024-11-08
 */
@Service
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products> implements IProductsService
{
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private IProductSkuService productSkuService;
    @Autowired
    private IProductSpecService productSpecService;

    @Autowired
    private IProductSkuSpecValueService productSkuSpecValueService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public ProductsDetailsResponse selectProductsById(Long id)
    {
        //根据id获取未逻辑删除的数据
        LambdaQueryWrapper<Products> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Products::getId,id);
        lqw.eq(Products::getIsDeleted, 0);
        Products products = this.getOne(lqw);
        ProductsDetailsResponse productsDetailsResponse = new ProductsDetailsResponse();
        BeanUtils.copyProperties(products, productsDetailsResponse);


        List<ProductSku> productSkuList = productSkuService.getProductSkuByProductId(products.getId());


        //根据skuId来获取商品规格属性，然后赋值给sku表
        for (ProductSku productSku : productSkuList) {
            List<ProductSpecResponse> productSpecResponseList = productSpecService.selectProductSpecListBySkuId(productSku.getId());
            productSku.setProductSpecResponseList(productSpecResponseList);

        }
        productsDetailsResponse.setProductSkuList(productSkuList);

        return productsDetailsResponse;
    }

    /**
     * 查询商品列表
     *
     * @param products 商品
     * @return 商品
     */
    @Override
    public List<ProductsDetailsResponse> selectProductsList(Products products)
    {
        List<Products> productsList = productsMapper.selectProductsList(products);
        //将productsList转化成productsDetailsResponseList
        List<ProductsDetailsResponse> productsDetailsResponseList  = new ArrayList<>();

        for (Products products1 : productsList){
            ProductsDetailsResponse productsDetailsResponse = new ProductsDetailsResponse();
            //复制
            BeanUtils.copyProperties(products1,productsDetailsResponse);
            //一个商品对应着多个sku
            List<ProductSku> productSkuList = productSkuService.getProductSkuByProductId(products1.getId());

            if (ObjectUtil.isEmpty(productSkuList))
                continue;

            //根据skuId来获取商品规格属性，然后赋值给sku表
            for (ProductSku productSku: productSkuList){
                List<ProductSpecResponse> productSpecResponseList = productSpecService.selectProductSpecListBySkuId(productSku.getId());
                productSku.setProductSpecResponseList(productSpecResponseList);

            }
            //将多条sku赋值给一个商品类型
            productsDetailsResponse.setProductSkuList(productSkuList);
            productsDetailsResponseList.add(productsDetailsResponse);
        }
        return productsDetailsResponseList;
    }

    /**
     * 新增商品
     *
     * @param productsRequest 商品
     * @return 结果
     */
    @Override
    @Transactional
    public Boolean insertProducts(ProductsRequest productsRequest)
    {
        try {

            Products products = new Products();
            BeanUtils.copyProperties(productsRequest, products);
            //商户id
            products.setMerchantId(1);
            boolean flag = this.save(products);

            //获取sku列表
            List<ProductSkuRequest> productSkuRequestList = productsRequest.getProductSkuRequestList();

            //对每一条sku进行保存
            for (ProductSkuRequest productSkuRequest : productSkuRequestList) {
                //从已经保存的商品中获取商品id
                productSkuRequest.setProductId(products.getId());

                ProductSku productSku = new ProductSku();
                BeanUtils.copyProperties(productSkuRequest, productSku);

                productSkuService.save(productSku);
                //对每一条sku获取到的商品规格属性值id，将它封装成ProductSkuSpecValue对象
                List<ProductSkuSpecValue> productSkuSpecValueList = productSkuRequest.getSpecValueIdList().stream().map(specValueId -> {
                    ProductSkuSpecValue productSkuSpecValue = new ProductSkuSpecValue();
                    //前端传过来
                    productSkuSpecValue.setSpecValueId(specValueId);
                    //获取上面 productSkuService.save(productSku);保存的数据id
                    productSkuSpecValue.setSkuId(productSku.getId());
                    return productSkuSpecValue;
                }).collect(Collectors.toList());
                //对每一条商品规格属性值关联sku的数据保存到数据库
                productSkuSpecValueService.saveBatch(productSkuSpecValueList);
            }

            if (flag) {
                return true;
            } else {
                throw new RuntimeException();
            }
        }catch (RuntimeException e){
            //批量删除图片和文件
            String[] imageUrls = productsRequest.getImageUrl().split(",");
            for (String s:imageUrls){
                FileUtils.deleteFileIfExists(s);
            }

            throw new RuntimeException("新增商品失败，且图片上传取消"+e);
        }
    }

    /**
     * 修改商品
     *
     * @param productsRequest 商品
     * @return 结果
     */
    @Override
    @Transactional
    public Boolean updateProducts(ProductsRequest productsRequest)
    {
        try {

            Products products = new Products();
            BeanUtils.copyProperties(productsRequest, products);
            boolean flag = this.updateById(products);

            List<ProductSkuRequest> productSkuRequestList = productsRequest.getProductSkuRequestList();

            for (ProductSkuRequest productSkuRequest : productSkuRequestList) {
                ProductSku productSku = new ProductSku();
                BeanUtils.copyProperties(productSkuRequest, productSku);
                productSkuService.updateById(productSku);


                LambdaUpdateWrapper<ProductSkuSpecValue> luw = new LambdaUpdateWrapper<>();
                luw.eq(ProductSkuSpecValue::getSkuId,productSku.getId());
                luw.eq(ProductSkuSpecValue::getIsDeleted,ProductConstant.NO_DELETE);
                luw.set(ProductSkuSpecValue::getIsDeleted,ProductConstant.DELETE);
                productSkuSpecValueService.update(luw);

                //对每一条sku获取到的商品规格属性值id，将它封装成ProductSkuSpecValue对象
                List<ProductSkuSpecValue> productSkuSpecValueList = productSkuRequest.getSpecValueIdList().stream().map(specValueId -> {
                    ProductSkuSpecValue productSkuSpecValue = new ProductSkuSpecValue();
                    productSkuSpecValue.setSpecValueId(specValueId);
                    productSkuSpecValue.setSkuId(productSku.getId());
                    return productSkuSpecValue;
                }).collect(Collectors.toList());

                productSkuSpecValueService.saveBatch(productSkuSpecValueList);

            }

            if (flag){
                return true;
            }else {
                throw new RuntimeException();
            }
        }catch (RuntimeException e){
            //批量删除图片和文件
            String[] strings = productsRequest.getImageUrl().split(",");
//            for (String s :strings){
//                FileUtils.deleteFileIfExists(s);
//            }

            throw new RuntimeException("修改商品失败"+e);
        }

    }

    /**
     * 批量删除商品
     *
     * @param productIds 需要删除的商品主键
     * @return 结果
     */
    @Override
    @Transactional
    public Boolean deleteProductsByIds(Integer[] productIds)
    {
        LambdaUpdateWrapper<Products> luw = new LambdaUpdateWrapper<>();
        luw
                //未逻辑删除
                .eq(Products::getIsDeleted,0)
                //遍历查询ids
                .in(Products::getId, Arrays.asList(productIds))
                //进行逻辑删除
                .set(Products::getIsDeleted, 1);
        boolean flag = this.update(luw);

        LambdaQueryWrapper<ProductSku> lqw = new LambdaQueryWrapper<>();
        lqw.select(ProductSku::getId);
        lqw.in(ProductSku::getProductId,Arrays.asList(productIds));
        lqw.eq(ProductSku::getIsDeleted,ProductConstant.NO_DELETE);
        List<ProductSku> productSkuList = productSkuService.list(lqw);

        List<Long> skuIdList = productSkuList.stream().map(ProductSku::getId).collect(Collectors.toList());

        LambdaUpdateWrapper<ProductSku> luw2 =new LambdaUpdateWrapper<>();
        luw2.in(ProductSku::getId,skuIdList);
        luw2.set(ProductSku::getIsDeleted,ProductConstant.DELETE);
        productSkuService.update(luw2);

        LambdaUpdateWrapper<ProductSkuSpecValue> luw3 = new LambdaUpdateWrapper<>();
        luw3.in(ProductSkuSpecValue::getSkuId,skuIdList);
        luw3.set(ProductSkuSpecValue::getIsDeleted,ProductConstant.DELETE);
        productSkuSpecValueService.update(luw3);



        if (flag){
            LambdaQueryWrapper<Products> lqw1 = new LambdaQueryWrapper<>();
            lqw1.select(Products::getImageUrl);
            lqw1.in(Products::getId,Arrays.asList(productIds));
            //查询出每一个商品的图片
            List<Products> productsList = this.list(lqw1);
            for (Products products:productsList){
                //对其中一个商品中多张图片，进行字符串分割成字符串数组
                String[] imageUrls = products.getImageUrl().split(",");
                //根据字符串数组进行遍历，以及进行图片删除
                for (String imageUrl:imageUrls){
                    FileUtils.deleteFileIfExists(imageUrl);
                }
            }
        }
        return flag;
    }

    /**
     * 删除单个商品信息
     *
     * @param productId 商品主键
     * @return 结果
     */
    @Override
    @Transactional
    public Boolean deleteProductsById(Integer productId)
    {
        LambdaUpdateWrapper<Products> luw = new LambdaUpdateWrapper<>();
        luw.eq(Products::getId,productId);
        luw.set(Products::getIsDeleted, ProductConstant.DELETE);

        LambdaQueryWrapper<ProductSku> lqw = new LambdaQueryWrapper<>();
        lqw.select(ProductSku::getId);
        lqw.eq(ProductSku::getProductId,productId);
        lqw.eq(ProductSku::getIsDeleted,ProductConstant.NO_DELETE);
        boolean flag = this.update(luw);
        List<ProductSku> productSkuList = productSkuService.list(lqw);

        List<Long> skuIdList = productSkuList.stream().map(ProductSku::getId).collect(Collectors.toList());

        LambdaUpdateWrapper<ProductSku> luw2 = new LambdaUpdateWrapper<>();
        luw2.in(ProductSku::getId,skuIdList);
        luw2.set(ProductSku::getIsDeleted,ProductConstant.DELETE);
        productSkuService.update(luw2);

        LambdaUpdateWrapper<ProductSkuSpecValue> luw3 = new LambdaUpdateWrapper<>();
        luw3.in(ProductSkuSpecValue::getSkuId,skuIdList);
        luw3.set(ProductSkuSpecValue::getIsDeleted,ProductConstant.DELETE);
        productSkuSpecValueService.update(luw3);

        if (flag){
            LambdaQueryWrapper<Products> lqw1 = new LambdaQueryWrapper<>();
            lqw1.select(Products::getImageUrl);
            lqw1.in(Products::getId,productId);
            lqw1.last("limit 1");
            //查询出商品的图片
            Products products = this.getOne(lqw1);
                //对其中一个商品中多张图片，进行字符串分割成字符串数组
                String[] imageUrls = products.getImageUrl().split(",");
                //根据字符串数组进行遍历，以及进行图片删除
                for (String imageUrl:imageUrls){
                    FileUtils.deleteFileIfExists(imageUrl);
                }
        }
        return flag;

    }

    @Override
    public List<ProductsExport> selectProductsExport(Products products) {
        return productsMapper.selectProductsExport(products);
    }

    public void validatorProductsParam(Products products){
        if (ObjectUtil.isEmpty(products.getName()))
            throw new RuntimeException("请填写商品名称");

        if(ObjectUtil.isEmpty(products.getCategoryId()))
            throw new RuntimeException("请填选择商品分类");

        if (ObjectUtil.isEmpty(products.getBrandId()))
            throw new RuntimeException("请填选择商品品牌");

    }
}
